<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/8
 * Time: 13:29
 */

namespace common\business\emppos;


use common\business\DbHandler;
use common\models\Employee;
use common\models\EmployeePosition;
use common\models\Position;
use common\result\ActionResult;

class EmployeePositionApiHandler extends DbHandler
{
    /**
     * @param $obj EmployeePosition
     * @return ActionResult
     */
    public function createEmployeePosition($obj){
        $this->updatePositionAndEmployee($obj);
        return $this->create($obj);
    }


    /**
     * @param $obj EmployeePosition
     */
    protected function updatePositionAndEmployee($obj){
        $positionInDb = Position::findOne([
            'number' => $obj->position_number
        ]);
        if ($positionInDb){
            $obj->position_id = $positionInDb->id;
        }
        $employeeInDb = Employee::findOne([
            'number' => $obj->employee_number
        ]);
        if($employeeInDb){
            $obj->employee_id = $employeeInDb->id;
        }
    }

    /**
     * @param EmployeePosition $newObj
     * @param EmployeePosition $oldObj
     * @return ActionResult
     */
    public function updateEmployeePosition($newObj, $oldObj = null){
        $this->updatePositionAndEmployee($newObj);
        if (!$oldObj){
            $oldObj = EmployeePosition::findOne([
                'number' => $newObj->number,
            ]);
        }
        return $this->update($newObj, $oldObj, [
            'employee_number',
            'employee_id',
            'employee_name',
            'position_number',
            'position_id',
            'position_name',
            'hr_status',
        ]);
    }
}